<template>
	<view class="pages-shopstore" :style="{background:pageColor}">
		<block v-if="isLoad">
			<block v-if="configInfo.plugAuth.partner">
				<fixed :zIndex="99">
					<view :style="{background:pageColor}">
						<image class="partner-bg" src="https://api.huixuananmm.com/admin/anmo/partner/partner-bg.png"
							mode="aspectFill"></image>
						<view class="rel">
							<!-- #ifndef H5 -->
							<uni-nav-bar :fixed="false" :shadow="false" :statusBar="true" :onlyLeft="true"
								:color="`#fff`" backgroundColor="transparent">
							</uni-nav-bar>
							<!-- #endif -->
							<view class="flex-between">
								<search class="flex-1" @input="toSearch" height="96rpx" :isScan="true" type="input"
									:padding="20" :radius="0" searchStyle="radius" backgroundColor="transparent"
									frontColor="#fff" placeholder="搜索您感兴趣的局">
								</search>
								<view class="pr-md flex-center" style="padding-left: 7rpx;" @tap="showScreen">
									<i class="iconfont iconshaixuan2 c-title"
										style="font-size: 12px;margin-right: 6rpx;"></i>
									<text class="f-desc c-title">筛选</text>
								</view>
							</view>
							<view class="pb-lg">
								<tab @change="handerTabChange" :list="cateList" :activeIndex="activeIndex*1"
									bgColor="transparent" :textBold="true" :activeColor="primaryColor" textColor="#333"
									height="70rpx" width="22%" lineRadius="0" lineHeight="12rpx" textFontSize="30rpx"
									activeTextFontSize="36rpx"></tab>
							</view>
						</view>
					</view>
				</fixed>
				<view class="partner-list pl-md pr-md">
					<block v-for="(item,index) in list.data" :key="index">
						<longbingbingPartnerListItem :info="item" :itemIndex="index"></longbingbingPartnerListItem>
					</block>
				</view>
				<load-more :noMore="list.current_page >= list.last_page && list.data.length > 0" :loading="loading">
				</load-more>
				<abnor v-if="!loading && list.data.length <= 0 && list.current_page == 1" :isCenter="true"></abnor>
				<auth :needAuth="!userInfo || (userInfo && (!userInfo.phone || !userInfo.nickName))"
					:type="!userInfo.phone ? 'phone' : 'userInfo'" @go="$util.goUrl({url: `/partner/pages/add`})">
					<view class="flex-center partner-add" :style="{background:primaryColor}">
						<i class="iconfont icon-add text-bold c-base" style="font-size: 22px;"></i>
					</view>
				</auth>
			</block>
			<block v-else>
				<abnor type="NOT_AUTH" :isCenter="true"></abnor>
			</block>

			<uni-popup ref="show_screen" type="bottom" :maskClick="true">
				<view class="screen-popup-content fill-base pd-lg">
					<view class="flex-center text-bold f-md-title">筛选</view>
					<view class="pt-lg">
						<view class="f-title pb-sm">活动报名时间</view>
						<view class="flex-warp flex-between">
							<view class="time-item flex-center mt-lg" @tap="handerTimeChange(item.id, 'time')" :style="{borderColor:check.time==item.id?primaryColor:'#666',
							color:check.time==item.id?'#fff':'#666',
							background:check.time==item.id?primaryColor:'#fff'}" v-for="(item,index) in timeList" :key="index">
								{{item.title}}</view>
						</view>
					</view>
					<view class="pt-lg">
						<view class="f-title pb-sm pt-md">活动费用</view>
						<view class="flex-warp flex-between">
							<view class="time-item flex-center mt-lg" @tap="handerTimeChange(item.id, 'money_type')"
								:style="{borderColor:check.money_type==item.id?primaryColor:'#666',
							color:check.money_type==item.id?'#fff':'#666',
							background:check.money_type==item.id?primaryColor:'#fff'}" v-for="(item,index) in moneyTypeList" :key="index">
								{{item.title}}</view>
						</view>
					</view>
					<view class="flex-center pt-lg mt-lg">
						<view class="screen-btn radius-16 flex-center mr-lg" @tap="reset">重置</view>
						<view class="screen-btn c-base flex-center radius-16" :style="{background:primaryColor}"
							@tap="determine">确定</view>
					</view>
					<view class="space-safe"></view>
				</view>
			</uni-popup>

			<view class="space-lg"></view>
			<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
			<longbingbing-tabbar :cur="8"></longbingbing-tabbar>

			<!-- #ifdef APP-PLUS -->
			<longbingbing-open-location-info ref="open_location_info" :isAdd="false"></longbingbing-open-location-info>
			<longbingbing-login-info></longbingbing-login-info>
			<longbingbing-app-check-auth type="location" ref="app_check_item"
				@confirm="toConfirmOpenLoca"></longbingbing-app-check-auth>
			<!-- #endif -->
			<longbingbing-change-user-type></longbingbing-change-user-type>
		</block>

		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import siteInfo from '@/siteinfo.js';
	import longbingbingPartnerListItem from "@/components/longbingbing-partner-list-item.vue"
	export default {
		components: {
			longbingbingPartnerListItem,
		},
		data() {
			return {
				isLoad: false,
				options: {},
				navTitle: '',
				loading: true,
				lockTap: false,
			}
		},
		computed: mapState({
			pageActive: state => state.partner.pageActive,
			cateList: state => state.partner.cateList,
			timeList: state => state.partner.timeList,
			check: state => state.partner.check,
			moneyTypeList: state => state.partner.moneyTypeList,
			param: state => state.partner.param,
			list: state => state.partner.list,
			tabList: state => state.partner.tabList,
			activeIndex: state => state.partner.activeIndex,
			configInfo: state => state.config.configInfo,
			isGzhLogin: state => state.user.isGzhLogin,
		}),
		async onLoad(options) {
			let launch = 0
			// #ifdef MP-WEIXIN 
			let {
				scene
			} = await uni.getLaunchOptionsSync()
			launch = scene // 1154：朋友圈
			options.launch = launch
			// #endif
			options = await this.updateCommonOptions(options)
			let {
				pid = 0,
			} = options
			options.pid = pid * 1
			this.options = options

			// #ifdef MP-WEIXIN
			uni.showShareMenu({
				menus: ['shareAppMessage', 'shareTimeline']
			})
			// #endif

			await this.$util.toAsyAccLogin()
			if (this.pageActive && !pid) {
				this.isLoad = true
				this.loading = false
				this.$util.hideAll()
				this.initNavTitle()
				return
			}
			await this.initIndex()
			this.updatePartnerItem({
				key: 'pageActive',
				val: true
			})
			this.initNavTitle()
		},
		async onShow() {
			this.initNavTitle(this.appShare ? 0 : 1)
			if (!this.location.lat && this.locaRefuse) {
				this.toResetUtilLoca()
			}
			let {
				status: coach_status = 0,
				coach_position = 0
			} = this.userCoachStatus
			let {
				realtime_location = 0
			} = this.configInfo

			if (this.pageActive && !realtime_location && coach_position && coach_status == 2) {
				this.$util.getCoachUtilLoca()
			}
			if (this.pageActive) {
				this.initIndex()
			}
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initRefresh()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		onShareTimeline() {
			let {
				navTitle: title
			} = this
			if (title.split('列表').length == 1) {
				title += `列表`
			}
			let {
				app_logo
			} = this.configInfo
			let imageUrl = app_logo || ''
			let {
				id: pid = 0
			} = this.userInfo
			let query = `pid=${pid}`
			return {
				title,
				imageUrl,
				query
			}
		},
		onShareAppMessage(e) {
			console.log(e)
			let index = 0
			if (e && e.target && e.target.dataset) {
				index = e.target.dataset.index || 0
			}
			let {
				id: pid = 0
			} = this.userInfo
			let {
				id,
				title,
				cover: imageUrl
			} = this.list.data[index]
			let path = `/partner/pages/detail?pid=${pid}&id=${id}`
			this.$util.log(path)
			return {
				title,
				imageUrl,
				path,
			}
		},
		watch: {
			locaRefuse(newval, oldval) {
				if (!newval) {
					this.toResetUtilLoca()
				}
			}
			// #ifndef H5
			,
			changeOnAddr(newval, oldval) {
				let {
					noloca,
				} = this.noChangeLoca
				if (newval && noloca) {
					this.initUtilLocaData()
				}
			},
			noChangeLoca(newval, oldval) {
				setTimeout(() => {
					let {
						lat,
						lng,
						unix = 0
					} = this.changeOnAddr
					let {
						noloca
					} = this.noChangeLoca
					let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
					if (noloca && ((!lat && !lng) || !unix || (unix && (cur_unix - unix >= 1)))) {
						this.getUtilLocation()
					}
				}, 800)
			}
			// #endif
		},
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo',
				'getTypeList', 'getPartnerList', 'addScanRecord', 'updateScanRecord', 'updateCommonOptions'
			]),
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem', 'updateMapItem',
				'updateDynamicItem', 'updatePartnerItem'
			]),
			async initIndex(refresh = false) {
				let {
					pid = 0,
						launch = 0
				} = this.options
				let code = this.scanRecordId
				// #ifdef H5
				code = this.$util.getQueryString('code')
				// #endif 
				if (pid && !code) {
					this.addScanRecord({
						type: 2,
						qr_id: pid,
						is_qr: 0
					})
				}
				let {
					id: uid = 0
				} = this.userInfo

				if (!this.configInfo.id || refresh || (pid && code && !uid)) {
					await this.getConfigInfo()
				}

				if (launch != 1154 && pid && !code && !uid) {
					await this.getUserInfo()
				}
				let {
					partner = false
				} = this.configInfo.plugAuth
				if (!partner) {
					this.isLoad = true
					this.loading = false
					this.$util.hideAll()
					return
				}
				let param = Object.assign({}, this.param, {
					title: ''
				});
				this.updatePartnerItem({
					key: 'param',
					val: param
				})
				await this.getTypeList()
				this.isNotLoca()
			},
			async initRefresh() {
				await this.initIndex(true)
			},
			async initNavTitle(isShow = 0) {
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				let {
					tabBar
				} = this.configInfo
				if (tabBar && tabBar.length > 0) {
					let ind = tabBar.findIndex(item => {
						return item.id == 8
					})
					let navTitle = ind == -1 ? '找搭子' : tabBar[ind].name
					this.navTitle = navTitle
					uni.setNavigationBarTitle({
						title: navTitle
					})
					if (this.scanRecordId) {
						this.updateScanRecord()
					}
					if (!isShow) {
						// #ifdef H5
						this.$jweixin.initJssdk(() => {
							this.toAppShare()
						})
						this.updateUserItem({
							key: 'appShare',
							val: false
						})
						// #endif
					}
				}
			},
			async toResetUtilLoca() {
				// #ifdef APP-PLUS
				let {
					lat: locaLat = 0
				} = this.location
				let {
					appCheckLocaStatus = null
				} = this
				if (!locaLat && appCheckLocaStatus == 1 && this.pageActive) {
					let {
						lng = 0,
							lat = 0
					} = await this.$util.getUtilLocation()
					if (!lat && !lng) return
					this.$refs.open_location_info.pShow = false
					await this.getList(1)
					let updateArr = ['updateServiceItem', 'updateTechnicianItem', 'updateMapItem',
						'updateDynamicItem'
					]
					updateArr.map(item => {
						this[item]({
							key: 'pageActive',
							val: false
						})
					})
				}
				// #endif
			},
			async toOpenLocation() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.ACCESS_FINE_LOCATION') ===
					'undetermined') {
					this.$refs.app_check_item.open()
				} else {
					this.toConfirmOpenLoca()
				}
				// #endif
				// #ifndef APP-PLUS
				this.toConfirmOpenLoca()
				// #endif
			},
			async toConfirmOpenLoca() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				this.initRefresh()
			},
			toAppShare() {
				let {
					id: pid = 0
				} = this.userInfo
				let {
					navTitle: title
				} = this
				if (title.split('列表').length == 1) {
					title += `列表`
				}
				let {
					siteroot
				} = siteInfo
				let url = siteroot.split('/index.php')[0]
				let href = `${url}/${this.portName}/#/pages/partner?pid=${pid}`
				let {
					app_logo
				} = this.configInfo
				let imageUrl = app_logo || ''
				this.$jweixin.showOptionMenu()
				this.$jweixin.shareAppMessage(title, '', href, imageUrl)
				this.$jweixin.shareTimelineMessage(title, href, imageUrl)
			},
			async isNotLoca() {
				let {
					location,
					locaRefuse
				} = this

				let {
					status: coach_status = 0,
					coach_position = 0
				} = this.userCoachStatus


				// #ifdef H5
				if (coach_position && coach_status == 2 && (location.lat && location.address != '暂未获取到位置信息')) {
					this.updateUserItem({
						key: 'isChangeCoachLoca',
						val: true
					})
				}
				// #endif


				// #ifdef APP-PLUS
				if (!locaRefuse && (!location.lat || (location.lat && location.address == '暂未获取到位置信息'))) {
					// #endif
					// #ifndef APP-PLUS
					if (!location.lat || (location.lat && location.address == '暂未获取到位置信息')) {
						// #endif

						// #ifdef MP-WEIXIN
						let privacyCheck = this.$refs.user_privacy.check()
						if (privacyCheck || typeof(privacyCheck) == 'string') {
							if (privacyCheck) {
								this.$refs.user_privacy.open()
							}
							this.isLoad = true
							this.loading = false
							this.$util.hideAll()
							return
						}
						// #endif

						// #ifndef H5
						if (coach_position && coach_status == 2) {
							let {
								lat: change_lat = 0,
								lng: change_lng = 0,
								unix = 0
							} = this.changeOnAddr
							let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
							let noloca = change_lat && change_lng && (unix && (cur_unix - unix < 3)) ? false : true
							if (!noloca) {
								let loca = Object.assign({}, this.location, {
									lat: change_lat,
									lng: change_lng,
									is_util_loca: 1
								})
								this.updateUserItem({
									key: 'location',
									val: loca
								})
							}
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca
								}
							})
							if (this.noChangeLoca.noloca) return
							this.initUtilLocaData()
						} else {
							this.getUtilLocation()
						}
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						return
						// #endif

						// #ifdef H5
						await this.$util.getUtilLocation()
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						// #endif
					}

					this.initUtilLocaData()
				},
				async getUtilLocation() {
						await this.$util.getUtilLocation()
						this.initUtilLocaData()
					},
					async initUtilLocaData() {
							// #ifndef H5
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca: false
								}
							})
							// #endif 
							await this.getList(1)
							let {
								lat = 0, lng = 0, is_util_loca = 0, isIp = true
							} = this.location
							if (lat && lng && is_util_loca) {
								this.$util.getMapInfo(isIp)
							}
						},
						toSearch(val) {
							this.param.title = val
							this.getList(1)
						},
						async getList(page) {
								if (page) {
									this.param.page = 1
									this.list.data = []
								}
								let {
									lat = 0, lng = 0
								} = this.location

								// #ifdef APP-PLUS
								if (!lat && !lng) {
									this.updatePartnerItem({
										key: 'list',
										val: {
											data: [],
											last_page: 1,
											current_page: 1
										}
									})
									this.isLoad = true
									this.loading = false
									this.$util.hideAll()
									return
								}
								// #endif

								let {
									list: oldList,
								} = this
								let param = Object.assign({}, this.param, {
									lat,
									lng
								});

								await this.getPartnerList(param)
								this.isLoad = true
								this.loading = false
								this.$util.hideAll()
							},
							goCate(e) {
								let {
									id,
									title,
								} = e
								let url = `/shopstore/pages/store-list?id=${id}&title=${title}`
								this.$util.goUrl({
									url
								})
							},
							handerTabChange(e) {
								this.updatePartnerItem({
									key: 'activeIndex',
									val: e
								})
								let param = Object.assign({}, this.param, {
									type_id: this.cateList[e].id
								});
								this.updatePartnerItem({
									key: 'param',
									val: param
								})
								this.getList(1)
							},
							showScreen() {
								this.$refs.show_screen.open()
							},
							handerTimeChange(id, type) {
								let check = this.$util.deepCopy(this.check)
								check[type] = id
								this.updatePartnerItem({
									key: 'check',
									val: check
								})
							},
							reset() {
								this.updatePartnerItem({
									key: 'check',
									val: {
										time: 0,
										money_type: 0
									}
								})
							},
							determine() {
								let param = Object.assign({}, this.param, this.check);
								this.updatePartnerItem({
									key: 'param',
									val: param
								})
								this.getList(1)
								this.$refs.show_screen.close()
							}
			}
		}
</script>


<style lang="scss">
	.partner-bg {
		height: 270rpx;
		width: 100%;
		top: 0;
		position: fixed;
	}

	.partner-add {
		width: 94rpx;
		height: 94rpx;
		border-radius: 94rpx;
		position: fixed;
		right: 20rpx;
		bottom: 180rpx;
	}

	.screen-popup-content {
		border-radius: 30rpx 30rpx 0 0;

		.time-item {
			height: 70rpx;
			border-radius: 70rpx;
			border: 1px solid transparent;
			width: 200rpx;
		}

		.screen-btn {
			width: 260rpx;
			height: 72rpx;
			background: #F2F2F2;
		}
	}
</style>